#ifndef _GlsxCommon_Singleton_H_
#define _GlsxCommon_Singleton_H_

#include "GlsxCommon.h"

#include "Core/Noncopyable.h"
#include "Thread/Thread.h"



// example.
// foo.h 
// class foo : public Singleton<foo> {}
// foo.cpp
// DECLARE_SINGLETON(foo)
// use: foo::instance().xx()

BEGIN_GLSX_NAMESPACE

template <class S> class SingletonHolder
{
public:
	SingletonHolder(): _pS(0) {}

	~SingletonHolder()
	{
		delete _pS;
	}

	S* get()
	{
		LockGuard<Mutex> lock(_m);
		if (!_pS) _pS = new S;
		return _pS;
	}

private:
	S* _pS;
	Mutex _m;
};

template<class T> class  Singleton : NonCopyable
{
public:
	static T& instance() 
	{
		return *_singleton.get();
	}
protected:
	static SingletonHolder<T> _singleton;
};

#define DECLARE_SINGLETON(T) \
	template<> SingletonHolder<T> Singleton<T>::_singleton;

END_GLSX_NAMESPACE

#endif